package light.head.start;

import java.util.Date;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import light.head.framework.entity.DBConnCfg;
import light.head.framework.utils.DatabaseUtils;
import light.head.framework.utils.DateUtils;

/**
 * @author janhang
 * @2010-12-14  下午04:59:25
 * 检查需要维持系统正常运行的基本数据
 */
public class CheckBaseData implements ServletContextListener {

	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("初始化基本数据....\n");
		
		try {
			String sql = "SELECT COUNT(*) FROM UserInfo WHERE email = 'admin@ish365.com'";
			DBConnCfg dci = DatabaseUtils.getHibernateCfg();
	
			DatabaseUtils.createConnection(dci.getUname(), dci.getPassword(), dci.getDriver(), dci.getConStr());
	
			if (Integer.parseInt(DatabaseUtils.findOneResult(sql, true)) == 0) {
				DatabaseUtils.createConnection(dci.getUname(), dci.getPassword(), dci.getDriver(), dci.getConStr());
				sql = "INSERT INTO UserInfo(realName, pwd, email, deleted, ct) " +
						"VALUES('admin', '21232f297a57a5a743894a0e4a801fc3', 'admin@ish365.com', 0, '" + 
						DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm") + "')";
				
				System.out.print("初始化用户信息....\t\t\t");
				if (DatabaseUtils.execSQL(sql, true) > 0)
					System.out.println("初始化成功!");
				else
					System.out.println("初始化失败!");
			}
			DatabaseUtils.closeConnection();
		} catch (Exception e) {
			System.out.println("初始化数据时发生异常: " + e.getMessage());
		}
		System.out.println("检查完毕\n");
	}

	
	public void contextDestroyed(ServletContextEvent sce) {
	}
}
